﻿using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.Domain.BusinessManage;
using SmartWMS.EntityFramework;
using SmartWMS.Server.BasicsDatumServer.WarehouseManagementService.Dto;
using SmartWMS.Server.BusinessServer.SalesReturns.Dto;
using SmartWMS.Server.Repository;
using SmartWMS.Server.WarehouseManage.HomeService.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.WarehouseManage.HomeService
{
    /// <summary>
    /// 首页数据
    /// </summary>
    public class HomeServices : IHomeServices
    {
        private readonly IRepository<Product> _product;
        private readonly IRepository<Accounting> _accounting;
        private readonly IRepository<ProcureManagement> _procureManagement;
        private readonly IRepository<SalesManageDetail> _salesManageDetail;
        private readonly IRepository<SalesManagement> _salesManagement;
        private readonly IRepository<Category> _category;
        private readonly SmartWMSContext smartWMSContext;
        private readonly IRepository<Shopping> _shopping;
        public HomeServices(IRepository<Product> product, IRepository<Accounting> accounting, IRepository<ProcureManagement> procureManagement, IRepository<SalesManageDetail> salesManageDetail, IRepository<Shopping> shopping, IRepository<SalesManagement> salesManagement,
            SmartWMSContext _smartWMSContext, IRepository<Category> category)
        {
            _product = product;
            _accounting = accounting;
            _procureManagement = procureManagement;
            _salesManageDetail = salesManageDetail;
            _shopping = shopping;
            _salesManagement = salesManagement;
            smartWMSContext = _smartWMSContext;
            _category = category;
        }
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        public async Task<HomeDtoPes> GetHome()
        {
            // 首页数据
            var list = new HomeDtoPes();
            // 获取产品列表
            var plist = await _product.GetAllListAsync();
            //库存总量
            list.TotalInventory = plist.Sum(x => x.Inventory);
            //库存总成本
            list.InventoryCosts = plist.Sum(x => (x.Price * x.Inventory));

            DateTime startDate = new DateTime(DateTime.Now.Year, 1, 1); // 今年的起始日期
            DateTime endDate = new DateTime(DateTime.Now.Year, 12, 31);   // 今年的结束日期
            //本年销售总额
            List<Accounting> thisYearSales = _accounting.GetListQuery()
                .Where(record => record.Paytime >= startDate && record.Paytime <= endDate && record.Type == "应收")
                .ToList();
            //本年采购总额
            List<Accounting> FYearSales = _accounting.GetListQuery()
                .Where(record => record.Paytime >= startDate && record.Paytime <= endDate && record.Type == "应付")
                .ToList();
            //本年总销售额
            list.SoldThisYear = thisYearSales.Sum(x => x.PayPrice);
            //本年总销售毛利
            list.GrossProfitForTheYear = thisYearSales.Sum(x => x.PayPrice) - FYearSales.Sum(x => x.PayPrice);

            //本周销售总额
            DateTime today = DateTime.Now;
            DayOfWeek currentDayOfWeek = today.DayOfWeek;
            int daysUntilMonday = (int)DayOfWeek.Monday - (int)currentDayOfWeek;
            DateTime startDatee = today.AddDays(daysUntilMonday - 7); // 本周的起始日期（周一）
            DateTime endDatee = startDatee.AddDays(6); // 本周的结束日期（周日）


            //int daysUntilMondays = ((int)DayOfWeek.Monday - (int)currentDayOfWeek + 7) % 7;
            //DateTime startDateThisWeek = today.AddDays(daysUntilMondays); // 本周的起始日期（星期一）

            //// 如果今天是星期日，那么结束日期就是今天
            //DateTime endDateThisWeek = currentDayOfWeek == DayOfWeek.Sunday ? today : startDateThisWeek.AddDays(6); // 本周的结束日期（星期天）


            List<Accounting> thisWeekSales = _accounting.GetListQuery().Where(record => record.Paytime >= startDatee && record.Paytime <= endDatee && record.Type == "应收").ToList();
            List<Accounting> FWeekSales = _accounting.GetListQuery().Where(record => record.Paytime >= startDatee && record.Paytime <= endDatee && record.Type == "应付").ToList();
            list.ThisWeeksTotal = thisWeekSales.Sum(x => x.PayPrice);
            //本周毛利
            list.GrossProfitThisWeek = thisWeekSales.Sum(x => x.PayPrice) - FWeekSales.Sum(x => x.PayPrice);

            //采购总额
            var clist = await _procureManagement.GetAllListAsync();
            var slist = await _shopping.GetAllListAsync();
            var sclist = (from a in clist
                          join b in slist on a.ProcurementCode equals b.ProcuremenCode
                          join c in plist on b.ProductId equals c.Id
                          select new
                          {
                              a.MakerTime,
                              c.Price,
                              b.BuyNumber
                          }).ToList();
            var bsclist = sclist.Where(x => x.MakerTime >= startDate && x.MakerTime <= endDate).ToList();
            //年采购总额
            list.PurchasedYear = bsclist.Sum(x => x.Price * x.BuyNumber);
            //月采购总额
            DateTime firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
            DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
            var bmsclist = sclist.Where(x => x.MakerTime >= firstDayOfMonth && x.MakerTime <= lastDayOfMonth).ToList();
            list.PurchasedMonth = bmsclist.Sum(x => x.Price * x.BuyNumber);

            return list;

        }




        /// <summary>
        /// 业务员销售排名
        /// </summary>
        /// <param name="overview"></param>
        /// <returns></returns>
        public async Task<Response<List<OverviewDto>>> ShowCount()
        {
            DateTime today = DateTime.Now;
            int quarter = (today.Month - 1) / 3 + 1; // 计算当前是第几季度
            DateTime firstDayOfQuarter = new DateTime(today.Year, (quarter - 1) * 3 + 1, 1);
            DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
            // 获取销售数据
            var list = await _salesManagement.GetAllListAsync();

            // 筛选出本季度内的销售数据
            list = list.Where(x => x.CreatorTime >= firstDayOfQuarter && x.CreatorTime <= lastDayOfQuarter).ToList();
            var resault = list.GroupBy(x => x.Creator).Select(x => new OverviewDto
            {
                Creator = x.Key,
                OrdersSum = x.Sum(x => x.OrdersSum)
            }).ToList();
            return Response<List<OverviewDto>>.Ok(resault);
        }
        /// <summary>
        /// 客户销售比较分析
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<ClientDto>>> ShowCountPro()
        {
            DateTime today = DateTime.Now;
            int quarter = (today.Month - 1) / 3 + 1; // 计算当前是第几季度
            DateTime firstDayOfQuarter = new DateTime(today.Year, (quarter - 1) * 3 + 1, 1);
            DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
            // 获取产品列表
            var list = await _product.GetAllListAsync();
            var SalesManagement = await _salesManagement.GetAllListAsync();
            var result = from A in list
                         join B in SalesManagement on A.Id equals B.ProductId
                         select new
                         {
                             A.ProductName,
                             A.Price,
                             B.CreatorTime
                         };

            // 筛选出本季度内的产品销售数据
            result = result.Where(x => x.CreatorTime >= firstDayOfQuarter && x.CreatorTime <= lastDayOfQuarter);
            // var list = await _product.GetAllListAsync();
            var result1 = result.GroupBy(x => x.ProductName).Select(x => new ClientDto
            {
                ProductName = x.Key,
                Price = x.Sum(x => x.Price)
            }).ToList();
            return Response<List<ClientDto>>.Ok(result1);
        }

        /// <summary>
        /// 仓库销售比较分析
        /// </summary>
        /// <returns></returns>
        public Task<Response<List<WarehouseDtos>>> ShowCountWarehouse()
        {
            DateTime today = DateTime.Now;
            int quarter = (today.Month - 1) / 3 + 1; // 计算当前是第几季度
            DateTime firstDayOfQuarter = new DateTime(today.Year, (quarter - 1) * 3 + 1, 1);
            DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
            //获取库存台账列表
            var inventorybook = smartWMSContext.InventoryBook.Where(x => x.InventoryBookDate >= firstDayOfQuarter && x.InventoryBookDate <= lastDayOfQuarter).ToList();
            var warehouse = smartWMSContext.Warehouse.ToList();
            var result = from A in warehouse
                         join B in inventorybook on A.Id equals B.WarehouseId
                         select new
                         {
                             A.Name,
                             B.Number
                         };
            var list = result.GroupBy(x => x.Name).Select(x => new WarehouseDtos
            {
                Name = x.Key,
                Number = x.Sum(x => x.Number)
            }).ToList();
            return Task.FromResult(Response<List<WarehouseDtos>>.Ok(list));
        }
        /// <summary>
        /// 统计存放销售比较分析
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<productDto>>> ShowproductDto()
        {
             DateTime today = DateTime.Now;
            int quarter = (today.Month - 1) / 3 + 1; // 计算当前是第几季度
            DateTime firstDayOfQuarter = new DateTime(today.Year, (quarter - 1) * 3 + 1, 1);
            DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
            // 获取产品列表
            var list = await _product.GetAllListAsync();
            // 获取产品分类列表
            var categor = await _category.GetAllListAsync();
            var result = from A in list
                         join B in categor on A.ProductTypeId equals B.Id
                         select new
                         {
                             B.CategoryName,
                             A.Inventory,
                             B.CreateTime // 假设产品表中有日期字段
                         };

            // 在这里加入日期过滤条件，只选择当前季度的数据
            result = result.Where(x => x.CreateTime >= firstDayOfQuarter && x.CreateTime <= lastDayOfQuarter);

            var totalInventory = result.Sum(x => x.Inventory); // 计算总库存数量
            var resault = result.GroupBy(x => x.CategoryName).Select(x => new productDto
            {
                CategoryName = x.Key,
                Inventory = x.Sum(x => x.Inventory),
                Percentage = (double)x.Sum(x => x.Inventory) / totalInventory * 100,// 计算百分比
                PercentageFormatted = ((double)x.Sum(x => x.Inventory) / totalInventory).ToString("P2")
            }).ToList();
            return Response<List<productDto>>.Ok(resault);
        }



    }
}
